import React from 'react';
import { useState, useEffect } from 'react';
import OrderTabs from './components/OrderTabs';
import './OrderPage.css';
import axios from 'axios'
import { useNavigate } from 'react-router-dom';

const Daizhifu = () => {

  const navigate = useNavigate()
  const [list, setList] = useState([])
  const getList = async () => {
    await axios.post('http://localhost:3010/roomDingList')
      .then(res => {
        if (res.data.code == 200) {
          setList(res.data.list)
        }
      })
  }

  useEffect(() => {
    getList()
  }, [])

  // 格式化日期为 YYYY/M/D
  const formatDate = (dateString) => {
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = date.getMonth() + 1; // 月份从0开始
    const day = date.getDate();
    return `${year}/${month}/${day}`;
  };

  const DateObj = (dataStr) => {
    const month = parseInt(dataStr.split('月')[0])
    const day = parseInt(dataStr.split('月')[1].replace('日'))
    const dataObj = new Date(new Date().getFullYear(), month - 1, day)
    return dataObj
  }

  //待入住
  const paynow = async (_id) => {
    await axios.post(`http://localhost:3010/updateRoom`, { _id: _id, status: '待入住' })
      .then(res => {
        if (res.data.code == 200) {
          getList()
        }
      })

    // 回显\


    const val = list.find(e => e._id == _id)
    console.log(val);
    val.start.slice(0,5)
    const start = val.start.slice(5,7) + '月' + val.start.slice(8,10) + '日'
    const end = val.end.slice(5,7) + '月' + val.end.slice(8,10) + '日'
    
    
    navigate("/order", { state: { val: {
      ...val,
      start:start,
      end:end
    }, jument: '徐铭颢' } })

  }

  return (
    <div className="order-page">
      <OrderTabs />
      <div className="order-content">
        {
          list.map((item) => {
            if (item.status == '待支付')
              return (
                <div className="order-item" key={item._id}>
                  <div className="hotel-info">
                    <h3>{item.hname}</h3>
                    <p className="room-type">{item.room}</p>
                    <p className="time">入住时间：{formatDate(item.start)}</p>
                    <p className="time">退房时间：{formatDate(item.end)}</p>
                    <p className="status mount">待支付</p>
                    <div className="price-row">
                      <span className="price">等待支付：￥{item.price}</span>
                      <button className="pay-btn" onClick={() => paynow(item._id)}>立即支付</button>
                    </div>
                  </div>
                </div>
              )
          })
        }
        <p style={{ textAlign: 'center', fontSize: '0.3rem', marginTop: '0.5rem', color: 'gray' }}>没有更多订单了 ~</p>
      </div>
    </div>
  );
};

export default Daizhifu;